﻿using System.Text.Json;
using System.Text;
using System;
using JWT.Serializers;
using JWT;
using JWT.Algorithms;

namespace MediumApi.Tools
{
    public class TokenHelpers
    {
        public class PlayloadDto
        {
            public string UserId { get; set; }
            public int RoleId { get; set; }
            public string Ticks { get; set; }
        }
        public class UserTicketResult
        {
            /// <summary>
            /// 
            /// </summary>
            public string Token { get; set; }

            /// <summary>
            /// 
            /// </summary>
            public DateTime ExpriedTime { get; set; }
        }

        public static readonly string secretKey = AppSettingHelper.GetConfig("Token")["Secret"];
        public static string Encode(PlayloadDto playloadDto)
        {
            byte[] key = Encoding.UTF8.GetBytes(secretKey);
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//加密方式
            IJsonSerializer serializer = new JsonNetSerializer();//序列化
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//base64加解密
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            string token = encoder.Encode(playloadDto, key);//生成令牌
            return token;
        }

        public static PlayloadDto DecodeToObject(string token, bool verify = true)
        {
            try
            {
                byte[] key = Encoding.UTF8.GetBytes(secretKey);
                IJsonSerializer serializer = new JsonNetSerializer();//序列化
                IDateTimeProvider provider = new UtcDateTimeProvider();
                IJwtValidator validator = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//base64加解密
                IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//加密方式
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
                //解密
                var json = decoder.DecodeToObject<PlayloadDto>(token, key, verify);
                return json;
            }
            catch 
            {
                return null;
            }
        }

        public static string Decode(string token, bool verify = true)
        {
            byte[] key = Encoding.UTF8.GetBytes(secretKey);
            IJsonSerializer serializer = new JsonNetSerializer();//序列化
            IDateTimeProvider provider = new UtcDateTimeProvider();
            IJwtValidator validator = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//base64加解密
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//加密方式
            IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
            //解密
            var json = decoder.Decode(new JwtParts(token), true);
            return json;
        }
        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static UserTicketResult GetTicketWithCache(string userId,int roleId)
        {
            //设置时间
            var expriedTime = DateTime.Now.AddYears(10);
            PlayloadDto playloadDto = new PlayloadDto()
            {
                UserId = userId,
                RoleId = roleId,
                Ticks = expriedTime.ToString()
            };
            //var gettoken = Redis.Get(userId);
            //if (gettoken != null)
            //{
            //    var json = TokenHelpers.DecodeToObject(gettoken);
            //    if (DateTime.Now < Convert.ToDateTime(json.Ticks))
            //    {
            //        UserTicketResult user = new UserTicketResult()
            //        {
            //            Token = gettoken,
            //        };
            //        return user;
            //    }
            //}
            var token = TokenHelpers.Encode(playloadDto);
            var ticket = new UserTicketResult
            {
                Token = token,
                ExpriedTime = expriedTime
            };
            //Redis.Add(userId, token);
            return ticket;
        }
    }
}
